<template>
  <div>
    <Breadcrumb :items="['系统管理', '租户管理']" />
    <a-card class="general-card" title="租户管理">
      <template #extra>
        <a-space direction="horizontal" :size="18">
          <a-button v-authorities="[SYS_PM.SYS_TENANT_READ]" type="primary" :loading="loading" @click="refresh">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
          <a-button @click="tenantSearchModel.resetFields()">
            <template #icon>
              <icon-refresh />
            </template>
            重置
          </a-button>
        </a-space>
      </template>

      <a-form
        ref="tenantSearchModel"
        :model="searchModel"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left"
      >
        <a-row :gutter="16">
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item field="tenantId" label="租户id">
              <a-input
                v-model="searchModel.tenantId"
                allow-clear
                placeholder="请输入租户id"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item field="name" label="租户名">
              <a-input
                v-model="searchModel.name"
                allow-clear
                placeholder="请输入租户名"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!--分割线-->
      <a-divider direction="horizontal" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button v-authorities="[SYS_PM.SYS_TENANT_WRITE]" type="primary" @click="onCreate">
              <template #icon>
                <icon-plus />
              </template>
              添加
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        :columns="tableColumns"
        :data="tbData"
        :loading="loading"
        row-key="id"
        :pagination="pagination"/>
    </a-card>
    <tenant-modal ref="tenantModal" @refresh="refresh"/>
    <tenant-joins-authority ref="tenantJoinsAuthority"/>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, ref } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import TenantModal from '@/views/system/tenant/components/tenant-modal.vue'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import TenantJoinsAuthority from '@/views/system/tenant/components/tenant-joins-authority.vue'
import usePaging from '@/hooks/paging'
import useLoading from '@/hooks/loading'
import { deleteById, listWithPagination } from '@/api/modules/system/tenant'
import type { TenantParam, TenantVo } from '@/types/modules/system'
import type { PaginationProps } from '@arco-design/web-vue'
import dayjs from "dayjs";
import { SYS_PM } from "@/types/PM";

const tableColumns = [{
  title: '租户id',
  dataIndex: 'tenantId',
}, {
  title: '租户名',
  dataIndex: 'name'
}, {
  title: 'logo',
  render: ({ record }: { record: any }) => {
    return  <a-image
    width="70px"
    src={record.logo}
    preview={false}
    />
  }
},{
  title: '状态',
  render: ({ record }: { record: any }) => {
    return <a-switch
      type="round"
      unchecked-color="#F53F3F"
      v-model:model-value={record.enabled}
      checked-value={true}
      unchecked-value={false}
      disabled={true}
      v-slots={{
        checked: () => <span>正常</span>,
        unchecked: () => <span>异常</span>
      }}>
    </a-switch>
  }
}, {
  title: '开始时间',
  render: ({ record }: { record: any }) => {
    return dayjs(record.startTime).format('YYYY-MM-DD HH:mm:ss')
  }
}, {
  title: '结束时间',
  render: ({ record }: { record: any }) => {
    return dayjs(record.endTime).format('YYYY-MM-DD HH:mm:ss')
  }
},{
  title: "操作",
  width: 330,
  align: "right",
  fixed: "right",
  render: ({ record }: { record: any }) => {
    return <>
      <a-button
        v-authorities={Array.of(SYS_PM.GRANT_TENANT_AUTHORIZATION)}
        type="text"
        size="small"
        onClick={() => onJoinsAuthority(record.tenantId)}
        v-slots={{
          icon: () => <icon-robot-add />,
          default: () => '分配权限'
        }}>
      </a-button>
      <a-button v-authorities={Array.of(SYS_PM.SYS_TENANT_READ)} type="text" size="small" onClick={() => onPreview(record.id)}>
        预览
      </a-button>
      <a-button v-authorities={Array.of(SYS_PM.SYS_TENANT_WRITE)} type="text" size="small" onClick={() => onUpdate(record.id)}>
        编辑
      </a-button>
      <a-popconfirm content={`确定删除 '${record.name}' 吗?`} type="warning" onOk={() => onDelete(record.id)}>
        <a-button v-authorities={Array.of(SYS_PM.SYS_TENANT_WRITE)} type="text" size="small" status="danger">
          删除
        </a-button>
      </a-popconfirm>
    </>
  }
}]

const searchModel = ref<TenantParam>({});
const tbData = ref<TenantVo[]>([]);
const tenantSearchModel = ref<any>()
const tenantModal = ref<any>(null);
const tenantJoinsAuthority = ref<any>(null)
const { pageable, prevPage } = usePaging();
const { loading, setLoading } = useLoading();

const pagination = ref<PaginationProps>({
  defaultCurrent: 1,
  defaultPageSize: 10
});

const refresh = async () => {
  setLoading(true);
  const { data } = await listWithPagination(pageable.value, searchModel.value);
  pagination.value = {
    current: data.current,
    pageSize: data.size,
    total: data.total,
    showTotal: true,
    showPageSize: true
  };
  tbData.value = data.records;
  setLoading(false);
};

const onDelete = async (id: number) => {
  try {
    await deleteById(id);
    if (tbData.value.length <= 1) {
      prevPage();
    }
  } finally {
    await refresh();
  }
};

const onCreate = async () => {
  setLoading(true);
  await tenantModal.value.createHandle();
  setLoading(false);
};

const onUpdate = async (id: number) => {
  setLoading(true);
  await tenantModal.value.updateHandle(id);
  setLoading(false);
};

const onPreview = async (id: number) => {
  setLoading(true)
  await tenantModal.value.previewHandle(id);
  setLoading(false)
}

const onJoinsAuthority = async (tenantId: string) => {
  setLoading(true)
  await tenantJoinsAuthority.value.grantAuthorities(tenantId)
  setLoading(false)
}

onMounted(async () => {
  await refresh();
});
</script>

<script lang="tsx">
export default {
  name: 'Tenant'
}
</script>

<style scoped>

</style>
